import axios from "axios";
import Loading from "../components/loading";
import ReactDOM from "react-dom";

export default function request(option) {
  // (encodeURIComponent(cookie.load('cookie')))
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: "http://localhost:3000",
      timeout: 100000,
      xhrFields: { withCredentials: true },
    });

    // 当前正在请求的数量
    // let requestCount = 0

    // // 显示loading
    // function showLoading () {
    //     if (requestCount === 0) {
    //         var dom = document.createElement('div')
    //         dom.setAttribute('id', 'loading')
    //         document.body.appendChild(dom)
    //         ReactDOM.render(<Loading/>, document.getElementById('loading'))
    //     }
    //     requestCount++
    // }

    // // 隐藏loading
    // function hideLoading () {
    //     requestCount--
    //     if (requestCount === 0) {
    //         document.body.removeChild(document.getElementById('loading'))
    //     }
    // }

    instance.interceptors.request.use(
      (config) => {
        // if (config.headers.isLoading !== false) {
        //     showLoading()
        // }
        return config;
      },
      (err) => {
        // if (err.config.headers.isLoading !== false) {
        //     hideLoading()
        // }
        return err;
      }
    );

    instance.interceptors.response.use(
      (response) => {
        // if (response.config.headers.isLoading !== false) {
        //     hideLoading()
        // }
        return response.data;
      },
      (err) => {
        // (err.response.data.msg);
        if (err && err.response) {
          switch (err.response.status) {
            case 400:
              err.message = "请求错误";
              break;
            case 401:
              err.message = "未授权的访问";
              break;
            default:
              err.message = "其他错误信息";
          }
        }

        return err;
      }
    );

    instance(option)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
